<template>
  <div class="wrapper">
    <BreakSpace label="分组信息" :containerStyle="{ marginBottom: '10px' }" />
    <FormPanel
      ref="infoMain"
      :list="formList"
      :formType="type"
      :isSubmitBtn="false"
      :cols= "3"
    />
    <div>
      <BreakSpace label="车辆信息" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        :maxHeight = "200"
        ref="tableVin"
        :columns="columns"
        :params="fetchParams"
        :dataSource= "ttRpVhlPeriodSpVinDTOList"
        :datakey="'records'"
        :isColumnFilter = "false"
        :isSelectColumn="false"
        columnsRef="notification_maintain_index_01"
        :exportFileName="'车辆信息.xlsx'"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="addVIN()" v-if="type === 'show' ? false : true">添加车辆</multiuse-button>
          <multiuse-button size="small" type="primary"  :loading="exportLoading" v-if="type === 'show' ? false : true" :click="downloadTemplatePlus.bind()">下载车辆模板</multiuse-button>
          <multiuse-button size="small" icon="el-icon-upload" v-if="type === 'show' ? false : true" @click="showImportFun()">导入</multiuse-button>
        </template>
        <div style="padding-top: 1rem;"></div>
      </FilterTable>
    </div>
    <div>
      <BreakSpace label="包修信息" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        ref="tableCar"
        :columns="columns2"
        :params="fetchParams"
        :dataSource= "ttRpVhlPeriodSpPartDTOList"
        :datakey="'records'"
        :isColumnFilter = "false"
        :isSelectColumn="false"
        columnsRef="notification_maintain_index_01"
        :exportFileName="'备件信息.xlsx'"
        :onColumnsChange="columns2 => (this.columns2 = columns2)"
      >
        <template slot="controls" slot-scope="props">
<!--          <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="addrCar()" v-if="type === 'show' ? false : true">添加备件类型</multiuse-button>-->
      <!--   <multiuse-button size="small" type="primary"  :loading="exportLoading" v-if="type === 'show' ? false : true" :click="downloadTemplate.bind()">下载备件模板</multiuse-button>
          <multiuse-button size="small" icon="el-icon-upload" v-if="type === 'show' ? false : true" @click="showImportFun()">导入</multiuse-button>-->
        </template>
        <div style="padding-top: 1rem;"></div>
      </FilterTable>
<!--      <BaseDialog :visible.sync="visibleAdd" :title="'新增备件类型'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">-->
<!--        <AddCar @close="closeAdd" @saveCar="saveCar" :ttRpVhlPeriodSpPartDTOList="ttRpVhlPeriodSpPartDTOList" :formData="formData" ></AddCar>-->
<!--      </BaseDialog>-->
<!--      <BaseDialog :visible.sync="visibleEdit" :title="'编辑备件类型'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">-->
<!--        <EditCar @close="closeEdit" @editCarSave="editCarSave" :formData="formData" ></EditCar>-->
<!--      </BaseDialog>-->
      <BaseDialog :visible.sync="visibleAddVIN" :title="'查询VIN'" width="850px" destroyOnClose :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
        <AddVIN @close="closeAdd" @save="saveCarVin" :ttRpVhlPeriodSpVinDTOList="ttRpVhlPeriodSpVinDTOList" :rowData="rowData" ></AddVIN>
      </BaseDialog>
    </div>

    <div class="dialogBottmView">
      <el-button @click="saveDialog()" v-if="type === 'show' ? false : true" type="primary">保 存</el-button>
      <el-button @click="closeDialogTop()">关 闭</el-button>
    </div>

    <BaseDialog :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editSave" :url="`${config.uploadUrl}/api/cms_claimfac/specialUser/importExcelPart`"/>
    </BaseDialog>
  </div>
</template>

<script>
import {queryData,querySparePartDetail,downloadModelPlus,saveSpecialUserAndVinAndPart,downloadModel} from '@/api/claim/factory/SpecialUserWarrantyMaintain';
import AddCar from "./AddCar";
import AddVIN from "./AddVIN";
import EditCar from "./EditCar";
import { exportExcelFile } from '@/utils/index';
import { dictionary } from '@/utils/dictMixin';
import importExcel from './importExcel';
import config from '@/assets/js/config';
import { number } from '@/utils/validate';


export default {
  mixins: [dictionary],
  components: {
    AddCar,
    AddVIN,
    EditCar,
    importExcel
  },
  props: {
    rowData: {
      type: Object,
      required: true
    },
    type: {
      type: String,
      required: false
    }
  },
  data() {
    return {
      ttRpVhlPeriodSpVinDTOList : [],
      ttRpVhlPeriodSpPartDTOList:[],
      formList: this.createFormList(),
      columns: this.creatHeader(),
      columns2:this.creatHeader2(),
      exportLoading: false,
      fetchParams:[],
      showImport: false,
      spId:"",
      visibleAdd: false,
      visibleAddVIN: false,
      formData: {},
      visibleEdit:false,
      result:"",
      config:config
    };
  },
  // 页面加载完成 请求接口
  mounted() {
    console.log("rowData=====",this.rowData)
    queryData(this.rowData.spId).then( (res) => {
      console.log(res)
      this.ttRpVhlPeriodSpVinDTOList = res.data.ttRpVhlPeriodSpVinDTOList;
      console.log("ttRpVhlPeriodSpVinDTOList===",this.ttRpVhlPeriodSpVinDTOList )

    });
      querySparePartDetail(this.rowData.spId).then(result => {
        console.log(result)

        this.ttRpVhlPeriodSpPartDTOList = result.data;
        console.log("ttRpVhlPeriodSpPartDTOList===",this.ttRpVhlPeriodSpPartDTOList )

      });
  },
  methods: {
    async delFun(data) {
      console.log("data------------------------>",data)
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async () => {
        this.ttRpVhlPeriodSpVinDTOList = this.ttRpVhlPeriodSpVinDTOList.filter(item=>item.$index != data.$index);
        console.log(this.ttRpVhlPeriodSpVinDTOList)
        })
    },
    // Excel更新导入
    showImportFun() {
      this.showImport = true;
    },
    editSave(val) {
      this.showImport = false;
      let isRepeat = false;
      let repeatVin = '';
      console.log("this.ttRpVhlPeriodSpVinDTOList",this.ttRpVhlPeriodSpVinDTOList);
      console.log("ttRpVhlPeriodSpPartDTOList===",this.ttRpVhlPeriodSpPartDTOList )
      console.log("val.tmVehicleVoList",val.tmVehicleVoList);
      if (this.ttRpVhlPeriodSpVinDTOList.length !== 0 && val.tmVehicleVoList){
        this.ttRpVhlPeriodSpVinDTOList.forEach(item =>{
          val.tmVehicleVoList.forEach(x =>{
            if(item.vin === x.vin && !isRepeat){
              isRepeat = true;
              repeatVin = item.vin;
              return this.$notify.error({ title: '提示信息', message: `此VIN: ：${repeatVin} 已存在,请核实` });
            }
          })
        });
      }
      if (this.ttRpVhlPeriodSpPartDTOList.length !== 0 && val.tmVehicleVoPartList){
        this.ttRpVhlPeriodSpPartDTOList.forEach(item =>{
          val.tmVehicleVoPartList.forEach(x =>{
            if(item.partType === x.partType && !isRepeat){
              isRepeat = true;
              return this.$notify.error({ title: '提示信息', message: `导入重复备件：${this.createDictText(x.partType, "5509")}，请核实数据` });
            }
          })
        });
      }
      if(!isRepeat){
        if (val.tmVehicleVoList){
          this.$refs.tableVin.EXECUTE_INSERT(val.tmVehicleVoList);
          let sizeVIN = val.tmVehicleVoList.length;
          if (sizeVIN !== 0) {
            this.$notify.success({ title: '提示信息', message: `导入成功：${sizeVIN} 条VIN！` });
          }else {
            return this.$notify.error({ title: '提示信息', message: "请核实导入数据" });
          }
        }else{
          if (val.tmVehicleVoPartList){
            this.$refs.tableCar.EXECUTE_INSERT(val.tmVehicleVoPartList);
            let size = val.tmVehicleVoPartList.length;
            if (size !== 0) {
              return this.$notify.success({ title: '提示信息', message: `导入成功：${size} 条备件信息！` });
            }
          }
          return this.$notify.error({ title: '提示信息', message: "请核实导入数据" });
        }
      }
    },
    //下载车辆模板
    downloadTemplate() {
      this.$confirm('此操作将下载备件模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        downloadModelPlus().then(res => {
          exportExcelFile(res.data, '特殊车辆模板');
          this.exportLoading = false;
        });
      });
    },
    //下载备件模板
    downloadTemplatePlus() {
      this.$confirm('此操作将下载车辆模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.exportLoading = true;
        downloadModel().then(res => {
          exportExcelFile(res.data, '特殊车辆模板');
          this.exportLoading = false;
        });
      });
    },
    addrCar(){
     this.visibleAdd = true;
    },
    saveCar(val) {
      this.visibleAdd = false;
      console.log("car=======",val)
      this.$refs.tableCar.EXECUTE_INSERT(val);
      console.log("ttRpVhlPeriodSpPartDTOList=================",this.ttRpVhlPeriodSpPartDTOList)

    },
    editCar(val){
      this.formData = val;
      console.log("formData===========",this.formData)
      this.visibleEdit = true;
    },
    editCarSave(val){
      this.visibleEdit = true;
      this.ttRpVhlPeriodSpPartDTOList.forEach(time =>{
        if(time.index === val.index){
          time.partType = val.partType
          time.vpMile = val.vpMile
          time.vpPeriod = val.vpPeriod
          time.vpStatus = val.vpStatus
        }
        this.visibleEdit = false;
      })
    },
    saveCarVin(val){
      this.visibleAddVIN = false;
      let length = this.ttRpVhlPeriodSpVinDTOList.length;
      val.forEach((item,index) =>{
        item.$index = length + index + 1;
      });
      this.$refs.tableVin.EXECUTE_INSERT(val)
      //this.ttRpVhlPeriodSpVinDTOList.push(...val);

    },

    closeAdd() {
      this.visibleAdd = false;
      this.visibleAddVIN = false;
    },
    closeEdit() {
      this.visibleAdd = false;
      this.visibleAddVIN = false;
      this.visibleEdit = false;
    },
    addVIN(){
      this.visibleAddVIN = true;
    },

    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '分组代码',
          filterable: true,
          fieldName: 'groupCode',
          readonly: true, // 只读
          disabled: true, //置灰
          initialValue: this.rowData['groupCode'],
        },
        {
          type: 'INPUT',
          label: '分组名称',
          filterable: true,
          fieldName: 'groupName',
          disabled:this.type === 'show' ? true : false,
          placeholder: '请选择分组名称...',
          initialValue: this.rowData['groupName'],
          rules: [{ required: true, message: '请输入分组名称...', trigger: 'change' },{ min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'change' }],
        },
        {
          type: 'SELECT',
          label: '状态',
          fieldName: 'vpStatus',
          filterable: true,
          disabled:this.type === 'show' ? true : false,
          placeholder: '请输入状态...',
          initialValue: this.rowData['vpStatus'],
          itemList: [{text: '停用', value: 0}, {text: '启用', value: 1}],
          rules: [{required: true, message: '请选择状态...', trigger: 'change'}]
        },
        {
          type: 'TEXT_AREA',
          label: '描述',
          maxlength: 300,
          fieldName: 'describe',
          placeholder: '请输入',
          initialValue: this.rowData['describe'],
          style: { width: '750px' },
          rows:2
        },
      ];
    },
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 70,
          sorter: true,
          render: (props) => {
            return <span>{props.row.$index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          hidden:this.type === 'show' ? true : false,
          render: (props, h) => {
            return (
              <multiuse-button size="mini" type="text" onClick={() => this.delFun(props.row)}>
                删除
              </multiuse-button>
            );
          },
        },
        { title: 'VIN号',dataIndex: 'vin', sorter: true },
        // { title: '运营类型',
        //   dataIndex: 'vpType',
        //   sorter: true,
        //   render: (props) => {
        //     return (
        //       <span>
        //         {
        //           this.createDictText(props.row.vpType, "2425")
        //         }
        //       </span>
        //     );
        //   },
        // },
      ]
    },
    creatHeader2() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          fixed: 'left',
          width: 70,
          sorter: true,
          render: (props) => {
            console.log(props)
            return <span>{props.row.$index + 1}</span>;
          },
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   hidden:this.type === 'show' ? true : false,
        //   render: (props, h) => {
        //     return (
        //       <multiuse-button size="mini" type="text" onClick={() => this.editCar(props.row)}>
        //         编辑
        //       </multiuse-button>
        //     );
        //   },
        // },
        {
          title: '备件类型',
          dataIndex: 'partType',
          render: (props) => {
            return (
              <span>
                {
                  this.createDictText(props.row.partType, "5509")
                }
              </span>
            );
          },
        },
        {
          title: '包修期(月)',
          dataIndex: 'vpPeriod',
          filterType:'number',
          disabled:this.type === 'show' ? true : false,
          editable:true,
          maxlength:9,
          editType:'number',
        },
        {
          title: '包修里程(KM)',
          dataIndex: 'vpMile',
          filterType:'number',
          disabled:this.type === 'show' ? true : false,
          editable:true,
          maxlength:9,
          editType:'number',
        },
        // {
        //   title: '是否有效',
        //   dataIndex: 'vpStatus',
        //   render: (props) => {
        //     return (
        //       <span>
        //         {
        //           props.row.vpStatus ? '否' : '是'
        //         }
        //       </span>
        //     );
        //   },
        // },
      ]
    },
    //保存（不验证）
    async saveDialog(){
      let dataVin = this.ttRpVhlPeriodSpVinDTOList;
      let dataCar = this.ttRpVhlPeriodSpPartDTOList;
      let [err,data] = await this.$refs.infoMain.GET_FORM_DATA();
      if(err) return;
      console.log('dataVin,dataCar,data',dataVin,dataCar,data);
      let params = {
        dataVin,
        dataCar,
        dataInfo:data,
        spId:this.rowData.spId,
      }
      // data = Object.assign({},data,{ ccId: this.ccId});
      let res = await saveSpecialUserAndVinAndPart(params);
      if (res.resultCode == 200) {
        this.$notify.success({title: '提示信息',message:'保存成功!'});
        this.$emit('close',{type:'refresh'});
      }
    },

    // 关闭当前页面操作
    // closeDialog(type){
    //   this.$emit('close', { visible: false ,type:type});
    // }
    closeDialogTop(){
      if (this.type !== 'show'){
        this.$confirm('确认关闭窗口吗？您所做的操作将不会被保存！', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.closeDialog('closeDialog');
          })
      }else {
        this.closeDialog('closeDialog');
      }
    },
    //取消操作
    closeDialog(type) {
      this.$emit('close', { visible: false,type:type});
    }


  }
};
</script>
<style scoped>
.wrapper {
  /*height: calc(100vh - 110px);*/
}
</style>
